package org.dean.webapps.projectname.exception.handler;

import org.dean.webapps.projectname.exception.GenericException;
import org.dean.webapps.projectname.utils.MessageUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dean.webapps.projectname.constants.MessageConstant;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Created by IntelliJ IDEA.
 * User: dean
 * Date: 9/5/11
 * Time: 2:19 PM
 * To change this template use File | Settings | File Templates.
 */
public class GenericMappingExceptionResolver extends SimpleMappingExceptionResolver {

    private Log log = LogFactory.getLog(GenericMappingExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
                                              HttpServletResponse response,
                                              Object handler,
                                              Exception ex) {
        ex.printStackTrace();
        ModelAndView mv = super.doResolveException(request, response, handler, ex);
        log.error(ex);
        if (mv != null && mv.getModel() != null) {

            if (!(ex instanceof GenericException)) {
                GenericException gex = (StringUtils.isEmpty(ex.getMessage())) ?
                        new GenericException(MessageUtils.getMessage(MessageConstant.UNKNOWN_EXCEPTION_MSG), ex)
                        : new GenericException(ex.getMessage(), ex);
                mv.getModel().put("exception", gex);
            }

//            mv.getModel().put("context-path", request.getContextPath());
        }
        return mv;
    }
}
